package com.seari.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

public class FilterOfIOR
{
	static String file1Path = "C:\\Users\\Rainbow\\Desktop\\TRAIN.xlsx";
	static String file2Path = "C:\\Users\\Rainbow\\Desktop\\IOR.xlsx";
	static String resultPath = "result.txt";
	static String baseUrl = "http://172.20.50.11/shior/shior/templates/show.html?page=train&line=#{line}&train=#{train}&type=#{type}&secret=64706C436458446159504E64325A5473676D48674C6961494E5635363136386F6C5558517233682B4466503268776D636D746F4A7675357A3478426774646532556B43636C6745614E54787579647A366832736448513D3D";
	static Map<String,Map<String,Ior>> iorMap = new HashMap<>();
	public static void main(String[] args) throws Exception
	{
		InputStream inputStream1 = new FileInputStream(new File(file1Path));
		InputStream inputStream2 = new FileInputStream(new File(file2Path));
		Workbook traingroupWorkbook = ImportExcelUtil.getWorkbook(inputStream1, file1Path);
		Workbook iorWorkbook = ImportExcelUtil.getWorkbook(inputStream2, file2Path);
		generateIorData(iorWorkbook);
		System.out.println(iorMap);
		processTraingroup(iorMap, traingroupWorkbook);
	}
	
	public static Map<String,Map<String,Ior>> generateIorData(Workbook iorWorkbook)
	{
		Map<String,Map<String,Ior>> resultMap = iorMap;
		Sheet sheet = iorWorkbook.getSheetAt(0);
		int count = 0;
		System.out.println("generateIorData:last line number:"+sheet.getLastRowNum());
		for(int i = 1; i <= sheet.getLastRowNum(); i++)
		{
			try
			{
				Row row = sheet.getRow(i);
				String lineId = row.getCell(0).getStringCellValue().substring(0,2);
				String trainType = row.getCell(0).getStringCellValue();
				String trainGroup = row.getCell(1).getStringCellValue();
				if(!resultMap.containsKey(lineId))
				{
					Ior ior = new Ior();
					ior.setLineId(lineId);
					ior.setTrainType(trainType);
					ior.setTrainGroup(trainGroup);
					HashMap<String, Ior> lineMap = new HashMap<>();
					lineMap.put(trainGroup, ior);
					resultMap.put(lineId, lineMap);
				}else {
					if(!resultMap.get(lineId).containsKey(trainGroup))
					{
						Ior ior = new Ior();
						ior.setLineId(lineId);
						ior.setTrainType(trainType);
						ior.setTrainGroup(trainGroup);
						HashMap<String, Ior> lineMap = (HashMap<String, Ior>) resultMap.get(lineId);
						lineMap.put(trainGroup, ior);
					}else {
						//do nothing
					}
				}
				count++;
			} catch (Exception e)
			{
				// TODO: handle exception
				System.out.println("exception:row Num:"+i);
			}
		}
		System.out.println("process ior data counts:"+count);
		return resultMap;
	}
	public static void processTraingroup(Map<String,Map<String,Ior>> iorMap,Workbook traingroupWorkbook)
	{
		Sheet sheet = traingroupWorkbook.getSheetAt(0);
		System.out.println("processTraingroup:last line number:"+sheet.getLastRowNum());
		List<Ior> resultList = new ArrayList<>();
		List<String> failList = new ArrayList<>();
		for(int i = 1; i <= sheet.getLastRowNum(); i++)
		{
			try
			{
				Row row = sheet.getRow(i);
				row.getCell(0).setCellType(CellType.STRING);
				String cell = row.getCell(0).getStringCellValue().trim();
				String lineId = guessLine(cell);
				if(iorMap.containsKey(lineId))
				{
					Map<String,Ior> lineMap = iorMap.get(lineId);
					row.getCell(1).setCellType(CellType.STRING);
					String atsTrain = row.getCell(1).getStringCellValue().trim();
					String prefixZero = 0+atsTrain;//前方补0
					String midZero = "";//中间补0，用于4位数据
					if(atsTrain.length()==4)
					{
						StringBuffer sb = new StringBuffer(atsTrain);
						sb.insert(2, "0");
						midZero = sb.toString();
					}
					String reduceZero = ""; //减0，用于6位数据
					if(atsTrain.length()==6)
					{
						if(atsTrain.substring(2, 3).equals("0"))
						{
							StringBuffer sb = new StringBuffer(atsTrain);
							sb.replace(2, 3, "");
							reduceZero = sb.toString();
						}
					}
					//匹配字符串
					if(lineMap.containsKey(atsTrain) && !checkAtsTrainExists(lineMap.get(atsTrain), "direct"))//直接匹配
					{
						System.out.println("direct match sucessfully:"+lineId+" "+atsTrain);
						Ior ior = lineMap.get(atsTrain);
						ior.setAtsTrain(atsTrain);
						resultList.add(ior);
					}else if (lineMap.containsKey(prefixZero) && !checkAtsTrainExists(lineMap.get(prefixZero), "prefixZero")) {//前方补0匹配
						System.out.println("prefixZero match sucessfully:"+lineId+" "+atsTrain);
						Ior ior = lineMap.get(prefixZero);
						ior.setAtsTrain(atsTrain);
						resultList.add(ior);
					}else if(StringUtils.isNotBlank(midZero) && lineMap.containsKey(midZero) && !checkAtsTrainExists(lineMap.get(midZero), "midZero")){
						System.out.println("midZero match sucessfully:"+lineId+" "+atsTrain);
						Ior ior = lineMap.get(midZero);
						ior.setAtsTrain(atsTrain);
						resultList.add(ior);
					}else if(StringUtils.isNotBlank(reduceZero) && lineMap.containsKey(reduceZero) && !checkAtsTrainExists(lineMap.get(reduceZero), "reduceZero")){
						System.out.println("reduceZero match sucessfully:"+lineId+" "+atsTrain);
						Ior ior = lineMap.get(reduceZero);
						ior.setAtsTrain(atsTrain);
						resultList.add(ior);
					}
				}
			} catch (Exception e)
			{
				// TODO: handle exception
				System.out.println("exception:row Num:"+i);
				e.printStackTrace();
			}
		}
		System.out.println("process:result size:"+resultList.size());
		System.out.println("failList size"+failList.size());
		writeToFile();
	}
	
	public static String guessLine(String cell)
	{
		String result = "";
		try
		{
			if(cell.toUpperCase().startsWith("CELL"))
			{
				result = cell.replace("CELL", "");
				if(result.length() < 4)
				{
					result = "0"+result;
				}
				result = result.substring(0,2);
			}else {
				if(cell.length() < 6)
				{
					result = "0"+cell;
				}else {
					result = cell;
				}
				result = result.substring(0,2);
			}
		} catch (Exception e)
		{
			System.out.println("guess error:"+cell);
			e.printStackTrace();
		}
		
		return result;
	}
	
	public static boolean checkAtsTrainExists(Ior ior,String methodName)
	{
		boolean result =false;
		if(StringUtils.isNotBlank(ior.getAtsTrain()))
		{
			result = true;
			System.out.println("ats train exists,"+ior.getLineId()+" "+ior.getAtsTrain()+" invoke method:"+methodName);
		}
		return result;
	}
	
	public static void writeToFile()
	{
		List<Ior> list = new ArrayList<>();
		for (Entry<String, Map<String, Ior>> entry : iorMap.entrySet())
		{
			for (Entry<String, Ior> iorEntry : entry.getValue().entrySet())
			{
				list.add(iorEntry.getValue());
			}
		}
		StringBuffer buffer = new StringBuffer();
		buffer.append("lineId").append("\t").append("trainType").append("\t")
		.append("trainGroup").append("\t").append("atsTrain").append("\t")
		.append("url").append("\n");
		for (Ior ior : list)
		{
			buffer.append(ior.getLineId()).append("\t");
			buffer.append(ior.getTrainType()).append("\t");
			buffer.append(ior.getTrainGroup()).append("\t");
			buffer.append(ior.getAtsTrain()).append("\t");
			buffer.append(baseUrl.replace("#{line}", ior.getLineId()).replace("#{train}", ior.getTrainGroup()).replace("#{type}", ior.getTrainType())).append("\t");
			buffer.append("\n");
		}
		FileWriter fw = null;
		try
		{
			// 如果文件存在，则追加内容；如果文件不存在，则创建文件
			File f = new File(resultPath);
			fw = new FileWriter(f, false);
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		PrintWriter pw = new PrintWriter(fw);
		pw.println(buffer.toString());
		pw.flush();
		try
		{
			fw.flush();
			pw.close();
			fw.close();
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}


class Ior{
	private String lineId;
	private String trainType;
	private String trainGroup;
	private String atsTrain;
	private String url;
	public String getLineId()
	{
		return lineId;
	}
	public void setLineId(String lineId)
	{
		this.lineId = lineId;
	}
	public String getTrainType()
	{
		return trainType;
	}
	public void setTrainType(String trainType)
	{
		this.trainType = trainType;
	}
	public String getTrainGroup()
	{
		return trainGroup;
	}
	public void setTrainGroup(String trainGroup)
	{
		this.trainGroup = trainGroup;
	}
	@Override
	public String toString()
	{
		return "ior [lineId=" + lineId + ", trainType=" + trainType + ", trainGroup=" + trainGroup + "]";
	}
	public String getAtsTrain()
	{
		return atsTrain;
	}
	public void setAtsTrain(String atsTrain)
	{
		this.atsTrain = atsTrain;
	}
	public String getUrl()
	{
		return url;
	}
	public void setUrl(String url)
	{
		this.url = url;
	}
	
}

